import axios from 'axios'
import {ElMessage} from "element-plus";

// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'


// 本地存储和访问token
const authItemName = "authorize";

const takeAccessToken = () => {
    const str = localStorage.getItem(authItemName)
        || sessionStorage.getItem(authItemName);
    if (!str) return null;
    const authObj = JSON.parse(str);
    // 判断过期时间
    if (new Date(authObj.expire) <= new Date()) {
        // 那就把这个token 删除
        deleteToken();
        ElMessage.warning('登录状态已过期，请重新登录!');
        return null;
    }
    return authObj.token;
}

// 保存token
const storeAccessToken = (token, expire, remember) => {
    const authObj = {
        token: token,
        expire: expire
    }
    console.log("保存token: ", authObj)
    const str = JSON.stringify(authObj);
    if (remember) localStorage.setItem(authItemName, str);
    else sessionStorage.setItem(authItemName, str);
}

// 删除token
const deleteToken = () => {
    localStorage.removeItem(authItemName);
    sessionStorage.removeItem(authItemName);
}


// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: 'http://localhost:8080',
    // 超时
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    }
})

//第三步 创建拦截器  http request 拦截器
service.interceptors.request.use(
    config => {
        const token = takeAccessToken();
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config
    },
    err => {
        return Promise.reject(err);
    })

// http response 拦截器
service.interceptors.response.use(
    response => {
        return response.data;
    }, error => {
        ElMessage.error(error.message);
        return Promise.reject(error); // 返回接口返回的错误信息
    });

export {service as request, storeAccessToken, deleteToken, takeAccessToken};